<?php

namespace app\controllers\h5;

use app\commission\PaidFinish;
use app\controllers\h5\base\H5Controller;
use app\models\group\Group;
use app\models\group\GroupFans;
use app\models\marketing\MarketingGroup;
use app\models\marketing\MarketingSecondKill;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\product\ProductAreaList;
use app\models\product\ProductSku;
use app\models\SetUserUp;
use app\models\system\SetApp;
use app\models\system\SetExpressCity;
use app\models\system\SetFlow;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCart;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\models\ZRegion;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class OrderController extends H5Controller
{
    /**
     * check order referrer
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheckReferrer()
    {
        $set = SetFlow::getLastOne();
        $order_referrer = boolval($set->order_referrer);

        if (!$order_referrer) {
            return $this->successEncode(['result' => true]);
        }

        $user = User::findOne(['id' => $this->user->id]);
        return $this->successEncode(['result' => $user->referrer_id > 0]);
    }

    public function actionQueryAccount()
    {
        $account = UserAccount::find()
            ->where(['user_id' => $this->user->id])
            ->asArray()
            ->one();

        return $this->successEncode($account);
    }

    public function actionQueryAddress()
    {
        $address = UserAddress::find()
            ->where(['user_id' => $this->user->id])
            ->andWhere(['status' => UserAddress::$statusMapping['OK']])
            ->orderBy(['is_default' => SORT_DESC, 'id' => SORT_DESC])
            ->with(['city'])
            ->asArray()
            ->all();

        foreach ($address as &$item) {
            $item['nickname'] = base64_decode($item['nickname']);

            // update city
            $item['city'] = [
                'province' => ZRegion::find()->where(['code' => $item['province_id']])->select(['name'])->scalar(),
                'city' => ZRegion::find()->where(['code' => $item['city_id']])->select(['name'])->scalar(),
                'area' => ZRegion::find()->where(['code' => $item['area_id']])->select(['name'])->scalar(),
            ];
        }

        return $this->successEncode($address);
    }

    public function actionQueryProduct()
    {
        /*
         * {"cart":true}
         *
         * {"price":"599.00","product_id":"141","quantity":1}
         *
         * {"quantity":5,"price":"7777777.00","score_cost":"100.00",
         * "product_sku_id":"20","selected_sku_value":["43","48","50"],
         * "selected_sku_text":["红色","中","加厚"],"product_id":"149"}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"create_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"random_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"group_id":"44"}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","create_group":true}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","group_id":"44"}
         */

        $data = $this->post();

        $isCart = isset($data['cart']) && $data['cart'];
        $isBuy = isset($data['product_id']) && $data['product_id'] > 0;
        // $isCreateGroup = isset($data['create_group']) && $data['create_group'];
        // $isJoinGroup = isset($data['group_id']) && $data['group_id'] > 0;
        $hasSku = isset($data['product_sku_id']) && $data['product_sku_id'] > 0;

        // 处理进云仓
        // $set = SetUserUp::getLastOne();

        if ($isCart) {
            $list = UserCart::find()
                ->where(['user_id' => $this->user->id])
                ->andWhere(['selected' => 1])
                ->orderBy(['id' => SORT_DESC])
                ->with([
                    'product', 'product.mainImage', 'product.scoreCost',
                    'sku', 'sku.image'
                ])
                ->asArray()
                ->all();

            $store = 0;
            foreach ($list as &$item) {
                $item['selected_sku_text'] = json_decode($item['selected_sku_text'], true);

                // 复购价格
                $item['product']['price'] = Product::getPriceByLevel($item['product']['id'], $this->user->id, $item['product']['price']);

                $store += $item['product']['store'] * $item['quantity'];
            }

            // 购物车
            return $this->successEncode([
                'list' => $list,
                'store' => $store,
                // 'is' => $store >= $set->store_begin,
                // ( 复购 不管 数量, 不进云仓 )
                // 'is' => false,
            ]);
        } else if ($isBuy) {
            $list = Product::find()
                ->where(['id' => $data['product_id']])
                ->with(['mainImage', 'scoreCost'])
                ->asArray()
                ->one();

            if ($hasSku) {
                $list['sku'] = ProductSku::find()
                    ->where(['id' => $data['product_sku_id']])
                    ->with(['image'])
                    ->asArray()
                    ->one();
                $list['selected_sku_text'] = $data['selected_sku_text'];
            } else {
                $list['sku'] = null;
                $list['selected_sku_text'] = null;
            }

            $list['quantity'] = $data['quantity'];

            unset($list['content'], $list['price_cost']);

            // 复购价格
            $list['price'] = Product::getPriceByLevel($list['id'], $this->user->id, $list['price']);

            return $this->successEncode([
                'list' => $list,
                'store' => $list['store'],
                // 'is' => $list['store'] >= $set->store_begin
            ]);
        } else {
            return $this->fail('!!!');
        }
    }

    protected function isRemoteCity($province_id)
    {
        $set = SetExpressCity::getLastOne();

        // 可能为空
        if ($set->province) {
            return in_array($province_id, $set->province);
        } else {
            return false;
        }
    }

    public function actionIsRemoteCity()
    {
        $province_id = $this->post('province_id');

        return $this->successEncode([
            'result' => $this->isRemoteCity($province_id)
        ]);
    }

    /**
     * create order
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCreateOrder()
    {
        /*
         * {"cart":true}
         *
         * {"price":"599.00","product_id":"141","quantity":1}
         *
         * {"quantity":5,"price":"7777777.00","score_cost":"100.00",
         * "product_sku_id":"20","selected_sku_value":["43","48","50"],
         * "selected_sku_text":["红色","中","加厚"],"product_id":"149"}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"create_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"random_group":true}
         *
         * {"price":"399.00","product_id":"147","quantity":1,"group_id":"44"}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","create_group":true}
         *
         * {"quantity":5,"price":"399.00","score_cost":0,
         * "product_sku_id":"12","selected_sku_value":["16","18"],
         * "selected_sku_text":["bbb","ccc"],"product_id":"148","group_id":"44"}
         */
        $data = $this->post();

        // 是不是进云仓
        $isStore = isset($data['check_store']) && $data['check_store'] == 2;

        $remark = isset($data['remark']) && $data['remark'];
        if (!$remark) {
            $remark = '';
        }

        $supplier = 0;

        // offline
        $offline = boolval($data['offline']);
        // $offline = false;
        // var_dump($offline);exit;

        $isCart = isset($data['cart']) && $data['cart'];
        $isBuy = isset($data['product_id']) && $data['product_id'] > 0;
        $isCreateGroup = isset($data['create_group']) && $data['create_group'];
        $isRandomGroup = isset($data['random_group']) && $data['random_group'];
        $isJoinGroup = isset($data['group_id']) && $data['group_id'] > 0;
        $hasSku = isset($data['product_sku_id']) && $data['product_sku_id'] > 0;

        $u = User::findOne(['id' => $this->user->id]);
        if ($u && !$u->mobile) {
            return $this->fail('您还没有授权手机号');
        }

        // need express
        $need_express = 1;
        if ($isCreateGroup || $isRandomGroup || $isJoinGroup) {
            $need_express = 0;
        }

        // user level
        // $u = User::findOne(['id' => $this->user->id]);

        // check second kill
        if (!$isCart) {

            $supplier = Product::find()
                ->where(['id' => $data['product_id']])
                ->select(['supplier_id'])
                ->scalar();

            if ($this->checkSecondKill($data['product_id'])) {
                return $this->customFail('您已经参数过该秒杀活动了!');
            }
            // 如果身份小于
            // if ($u->level < UserLevel::$keys['member']) {
            //     if ($this->checkFree($data['product_id'])) {
            //         // return $this->customFail('粉丝只能免费领取1次!');
            //         return $this->customFail('粉丝不能领取!');
            //     }
            // }

        } else {
            $ids = UserCart::find()
                ->where(['user_id' => $this->user->id])
                ->andWhere(['selected' => 1])
                ->select(['product_id'])
                ->asArray()
                ->all();

            if (!$ids) {
                return $this->fail('购物车为空,请勿重复下单');
            }

            $supplier = Product::find()
                ->where(['id' => $ids[0]])
                ->select(['supplier_id'])
                ->scalar();

            $ids = ArrayHelper::getColumn($ids, 'product_id');
            foreach ($ids as $id) {
                if ($this->checkSecondKill($id)) {
                    return $this->customFail('您已经参数过该秒杀活动了!');
                }
                // if ($u->level < UserLevel::$keys['member']) {
                //     if ($this->checkFree($id)) {
                //         // return $this->customFail('粉丝只能免费领取1次!');
                //         return $this->customFail('粉丝不能领取!');
                //     }
                // }

            }
        }

        // check address
        if (isset($data['address_id']) && $data['address_id'] > 0) {
            // $address = UserAddress::findOne(['id' => $data['address_id'], 'user_id' => $this->user->id]);
            $address = UserAddress::findOne([
                'id' => $data['address_id'],
                'user_id' => $this->user->id,
                'status' => UserAddress::$statusMapping['OK']
            ]);
            if (!$address) {
                return $this->customFail('收货地址错误');
            }
        } else {
            // 如果不是进云仓
            // var_dump($data);exit;
            if (!$isStore) {
                return $this->customFail('请选择地址~~~');
            }
        }

        // is remote city
        if (!$isStore) {
            $isRemoteCity = $this->isRemoteCity($address->province_id);
        } else {
            $isRemoteCity = false;
        }

        // products
        $products = [];
        if ($isCart) {
            $list = UserCart::find()
                ->where(['user_id' => $this->user->id])
                ->andWhere(['selected' => 1])
                ->orderBy(['id' => SORT_DESC])
                ->with([
                    'product', 'product.scoreCost',
                    'sku',
                ])
                ->asArray()
                ->all();
            foreach ($list as $item) {
                $v = [
                    'quantity' => $item['quantity'],
                    'product_id' => $item['product_id'],
                    'product_sku_id' => $item['product_sku_id'],
                    'selected_sku_value' => $item['selected_sku_value'],
                    'selected_sku_text' => $item['selected_sku_text'],
                    // v3 修改运费
                    'freight' => $isStore ? 0 : ($isRemoteCity ? $item['product']['remote_freight'] : $item['product']['freight']),
                ];

                // price
                if ($item['sku']) {
                    $price = $item['sku']['price'];
                } else {
                    $price = $item['product']['price'];
                }

                // 复购价格
                $price = Product::getPriceByLevel($item['product_id'], $this->user->id, $price);

                // score
                if (isset($item['product']['scoreCost']) && $item['product']['scoreCost']['total'] > 0) {
                    $v['price'] = $item['product']['scoreCost']['total'];
                    $v['score'] = $price;
                } else {
                    $v['price'] = $price;
                    $v['score'] = 0;
                }

                array_push($products, $v);
            }
        } else if ($isBuy) {

            // 84000 系列
            // if (ProductArea::checkB84000($data['product_id'])) {
            //     $my = User::findOne(['id' => $this->user->id]);
            //     if (in_array($data['product_id'], [$my->b841, $my->b842])) {
            //         return $this->customFail('请勿重复购买~~~');
            //     }
            // }

            $product = Product::find()
                ->where(['id' => $data['product_id']])
                ->with(['scoreCost'])
                ->asArray()
                ->one();

            if ($hasSku) {
                $product['sku'] = ProductSku::find()
                    ->where(['id' => $data['product_sku_id']])
                    ->asArray()
                    ->one();
            }

            $v = [
                'quantity' => $data['quantity'],
                'product_id' => $data['product_id'],
                'product_sku_id' => isset($data['product_sku_id']) ? $data['product_sku_id'] : 0,
                'selected_sku_value' => json_encode($this->post('selected_sku_value')),
                'selected_sku_text' => json_encode($this->post('selected_sku_text')),
                // v3 修改运费
                'freight' => $isStore ? 0 : ($isRemoteCity ? $product['remote_freight'] : $product['freight']),
            ];

            // price
            if ($hasSku && $product['sku']) {
                $price = $product['sku']['price'];
            } else {
                $price = $product['price'];
            }

            // 复购价格
            $price = Product::getPriceByLevel($data['product_id'], $this->user->id, $price);

            // score
            if (isset($product['scoreCost']) && $product['scoreCost']['total'] > 0) {
                $v['price'] = $product['scoreCost']['total'];
                $v['score'] = $price;
            } else {
                $v['price'] = $price;
                $v['score'] = 0;
            }

            array_push($products, $v);
        }

        if (empty($products)) {
            return $this->customFail('请选择下单商品');
        }

        // account
        $account = UserAccount::findOne(['user_id' => $this->user->id]);

        // calc (freight, price[sku_price], score)
        $total_freight = 0;
        $total_price = 0;
        $total_score = 0;
        $total_quantity = 0;
        foreach ($products as $product) {
            $total_freight += $product['freight'] * $product['quantity'];
            $total_price += $product['price'] * $product['quantity'];
            $total_score += $product['score'] * $product['quantity'];
            $total_quantity += $product['quantity'];
        }

        // total pay
        $total_pay = $total_score + $total_freight + $total_price;

        // use balance, score, platform_ticket, money
        $use_money = $total_freight + $total_price;
        $use_balance = 0;
        $use_score = 0;
        $use_platform_ticket = 0;

        // use score
        // todo 临时积分处理
        // if ($account->score < $total_score) {
        //     $use_money += $total_score - $account->score;
        //     $use_score = $account->score;
        // } else {
        //     $use_score = $total_score;
        // }

        // 这里可以理解成是消费积分
        // platform_ticket
        if ($use_money > 0) {
            // 只能复购区使用消费积分
            // 取消了
            // if (ProductAreaList::checkInArea($products[0]['product_id'], Product::$areaMap['REPEAT'])) {
            //     if ($account->platform_ticket >= $use_money) {
            //         $use_platform_ticket = $use_money;
            //         $use_money = 0;
            //     } else {
            //         $use_platform_ticket = $account->platform_ticket;
            //         $use_money -= $account->platform_ticket;
            //     }
            // }
        }

        // balance
        if ($use_money > 0) {
            if ($account->balance >= $use_money) {
                $use_balance = $use_money;
                $use_money = 0;
            } else {
                $use_balance = $account->balance;
                $use_money -= $account->balance;
            }
        }

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            // order
            $order = new Order();
            $order->is_platform = 1;
            $order->remark = $remark;
            $order->sn = Order::generateSn();
            $order->user_id = $this->user->id;
            $order->total_quantity = $total_quantity;
            $order->total_price = $total_price;
            $order->total_freight = $total_freight;
            $order->total_pay = $total_pay;
            $order->use_balance = $use_balance;
            // $order->use_score = $use_score;
            $order->use_platform_ticket = $use_platform_ticket;
            $order->use_money = $use_money;
            if ($offline) {
                $order->pay_type = -88;
                $order->pay_type_name = '线下打款';
            }
            $order->user_address = $data['address_id'];
            $order->status = Order::$statusMapping['NON_PAYMENT'];

            if ($isStore) {
                $order->is_store = 1;
                $order->store_box= $data['store_num'];

                // 放入云仓, 也是发货了 [后台支付也会改变这个状态]
                // $order->status = Order::$statusMapping['WAIT_RECEIVING'];

            }

            // 日志
            $chain = Chain::getReferrerChain($order->user_id);
            $log = [
                // 'user' => User::findOne(['id' => $order->user_id])->toArray(),
                'user' => User::find()->where(['id' => $order->user_id])->with(['level0'])->asArray()->one(),
                'chain' => $chain,
            ];
            $log = json_encode($log);
            $order->log = $log;

            // request params
            $order->request_params = json_encode($data);

            // 供应商
            $order->supplier_id = $supplier;

            // if ($isCreateGroup || $isJoinGroup || $isRandomGroup) {
            //     $order->is_group = 1;
            // }
            if (!$order->save()) {
                throw new \Exception('创建订单失败');
            }



            // balance logs
            if ($use_balance > 0) {
                UserBalance::addLog($this->user->id,
                    $account->balance, -$use_balance, $account->balance - $use_balance, '订单消费', $order->id);
            }

            // cart
            if ($isCart) {
                UserCart::deleteAll(['user_id' => $this->user->id, 'selected' => 1]);
            }

            // order item
            foreach ($products as $product) {
                $item = new OrderItem();
                $item->order_id = $order->id;
                $item->quantity = $product['quantity'];
                $item->product_id = $product['product_id'];
                $item->product_sku_id = $product['product_sku_id'];
                $item->selected_sku_value = $product['selected_sku_value'];
                $item->selected_sku_text = $product['selected_sku_text'];
                $item->freight = $product['freight'];
                $item->price = $product['price'];
                $item->score = $product['score'];
                // is express
                $item->is_express = $need_express;
                $item->save();
            }

            // group
            if (!$isCart) {

                // create group
                if ($isCreateGroup) {
                    $group = new Group();
                    $group->user_id = $this->user->id;
                    $group->product_id = $data['product_id'];
                    $group->status = 0;
                    $group->order_id = $order->id;
                    $group->save();

                    // add myself
                    $group_fans = new GroupFans();
                    $group_fans->group_id = $group->id;
                    $group_fans->user_id = $this->user->id;
                    $group_fans->order_id = $order->id;
                    $group->status = 0;
                    $group_fans->save();
                }

                // random group
                if ($isRandomGroup) {

                    // out
                    // $this->outGroup($data['product_id']);

                    $last_random_group = Group::find()
                        ->where(['is_random' => 1])
                        ->andWhere(['status' => 1])
                        ->andWhere(['product_id' => $data['product_id']])
                        ->orderBy(['id' => SORT_ASC])
                        ->one();
                    if (!$last_random_group) {
                        $last_random_group = new Group();
                        $last_random_group->is_random = 1;
                        $last_random_group->user_id = $this->user->id;
                        $last_random_group->product_id = $data['product_id'];
                        $last_random_group->status = 0;
                        $last_random_group->order_id = $order->id;
                        $last_random_group->save();

                        $fans = new GroupFans();
                        $fans->group_id = $last_random_group['id'];
                        $fans->user_id = $this->user->id;
                        $fans->order_id = $order->id;
                        $fans->status = 0;
                        $fans->save();
                    } else {

                        $check = GroupFans::findOne(['group_id' => $last_random_group['id'],
                            'user_id' => $this->user->id]);
                        if ($check) {
                            throw new \Exception('此轮您已经参与过了');
                        }

                        $fans = new GroupFans();
                        $fans->group_id = $last_random_group['id'];
                        $fans->user_id = $this->user->id;
                        $fans->order_id = $order->id;
                        $fans->status = 0;
                        $fans->save();

                        // $set = MarketingGroup::getLastOne();
                        // $group_quantity = $set->quantity;

                        // out
                        // $this->outFans($last_random_group['id']);

                        // group finish
                        // $count = GroupFans::find()
                        //     ->where(['group_id' => $last_random_group['id']])
                        //     ->count();
                        // if ($count == $group_quantity) {
                        //     $last_random_group->status = 2;
                        //     $last_random_group->save();
                        // }
                    }
                }

                // join group
                if ($isJoinGroup) {

                    // out
                    // $this->outGroup($data['product_id']);

                    // check group
                    if ($this->checkGroupFinish($data['group_id'])) {
                        throw new \Exception('此团已经结束');
                    }

                    $group = Group::findOne(['id' => $data['group_id']]);

                    if (!$group) {
                        throw new \Exception('此团不存在');
                    }

                    if ($group->user_id == $this->user->id) {
                        throw new \Exception('自己不能和自己玩');
                    }

                    // is exist
                    $check = GroupFans::findOne(['group_id' => $data['group_id'], 'user_id' => $this->user->id]);
                    if ($check) {
                        throw new \Exception('不能重复参与');
                    }

                    // out
                    // $this->outFans($data['group_id']);

                    // $set = MarketingGroup::getLastOne();
                    // $group_quantity = $set->quantity;
                    // $count = GroupFans::find()
                    //     ->where(['group_id' => $data['group_id']])
                    //     ->count();
                    // if ($count == $group_quantity) {
                    //     throw new \Exception('此团已满人');
                    // }

                    $group_fans = new GroupFans();
                    $group_fans->group_id = $data['group_id'];
                    $group_fans->user_id = $this->user->id;
                    $group_fans->order_id = $order->id;
                    $group_fans->status = 0;
                    $group_fans->save();
                }
            }

            // 由于有后台确认支付(或者前端重新支付), 余额可能会出现负
            // 所以这里要锁定余额, 完成支付后, 把锁定的清除
            // todo 一直没有支付, 需要把锁定的余额还回去, 比如30分钟未支付把订单取消, 还回去
            if ($use_balance > 0) {
                $account->balance -= $use_balance;
                $account->lock_balance += $use_balance;
                $account->save();
            }
            if ($use_platform_ticket > 0) {
                $account->platform_ticket -= $use_platform_ticket;
                $account->lock_platform_ticket += $use_platform_ticket;
                $account->save();
            }

            // order paid
            if ($use_money == 0) {
                PaidFinish::order($order);
            }

            $transaction->commit();
            return $this->successEncode([
                'order_id' => $order->id,
                'amount' => $use_money,
                'is_create' => $isCreateGroup,
                'is_join_random' => $isJoinGroup || $isRandomGroup
            ]);
        } catch (\Exception $e) {
            $transaction->rollBack();

            // var_dump($e->getTrace());

            // return $this->customFail($e->getMessage());
            return $this->customFail($e->getMessage() . ' ' . $e->getLine() . ' ' . $e->getFile());
        }
    }

    // private function outGroup($product_id) {
    //     $list = Group::find()
    //         ->where(['product_id' => $product_id])
    //         ->with(['order'])
    //         ->all();
    //
    //     foreach ($list as $item) {
    //         $status = $item['order']['status'];
    //         if (in_array($status, [Order::$statusMapping['NON_PAYMENT'], Order::$statusMapping['CANCEL']])) {
    //             // delete order
    //             $order = Order::findOne(['id' => $item['order']['id']]);
    //             $order->status = Order::$statusMapping['DELETE'];
    //             $order->save();
    //
    //             // delete group
    //             $item->delete();
    //         }
    //     }
    // }

    // private function outFans($group_id) {
    //     $list = GroupFans::find()
    //         ->where(['group_id' => $group_id])
    //         ->with(['order'])
    //         ->all();
    //
    //     foreach ($list as $item) {
    //         $status = $item['order']['status'];
    //         if (in_array($status, [Order::$statusMapping['NON_PAYMENT'], Order::$statusMapping['CANCEL']])) {
    //
    //             // delete order
    //             $order = Order::findOne(['id' => $item['order']['id']]);
    //             $order->status = Order::$statusMapping['DELETE'];
    //             $order->save();
    //
    //             // delete fans
    //             $item->delete();
    //         }
    //     }
    // }

    /**
     * get pay amount
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionGetAmount()
    {
        $order_id = $this->post('order_id');

        $model = Order::find()
            ->where(['id' => $order_id])
            ->andWhere(['user_id' => $this->user->id])
            ->one();
        if ($model) {

            // 是否使用第三方支付[如汇聚]
            $set = SetApp::getLastOne();

            return $this->successEncode([
                'amount' => $model->use_money,
                'sn' => $model->sn,
                'user_id' => $model->user_id,
                'third_pay' => $set['third_pay'] == 1
            ]);
        }

        return $this->fail();
    }

    public function actionCheckGroup()
    {
        $group_id = $this->post('group_id');

        if ($this->checkGroupFinish($group_id)) {
            return $this->customFail('此团已经结束');
        }

        return $this->success();
    }

    public function actionCheckSecondKill()
    {
        $product_id = $this->post('product_id');

        if ($this->checkSecondKill($product_id)) {
            return $this->customFail('您已经参与过该秒杀了');
        }

        return $this->success();
    }

    protected function checkGroupFinish($group_id)
    {
        $group = Group::findOne(['id' => $group_id]);

        if ($group && $group->status == 2) {
            return true;
        }
    }

    protected function checkSecondKill($product_id)
    {
        // $area_ids = ProductAreaList::getProductAreaList($product_id);

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['KILL'])) {
            $order = Order::find()
                ->andWhere(['user_id' => $this->user->id])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['>=', 'status', Order::$statusMapping['PAID']])
                ->select(['id'])
                ->column();
            if ($order) {

                // todo 这里没有处理商品的数量(包括购物车)
                $count = OrderItem::find()
                    ->where(['order_id' => $order])
                    ->andWhere(['product_id' => $product_id])
                    ->count();

                $set = MarketingSecondKill::getLastOne();

                if ($count >= $set->order_quantity) {
                    return true;
                }
            }
        }
    }

    // 免费领
    protected function checkFree($product_id)
    {
        // $area_ids = ProductAreaList::getProductAreaList($product_id);

        if (ProductAreaList::checkInArea($product_id, Product::$areaMap['FREE'])) {

            // 之前是只能领取1次, 现在改成了会员以上才能领取
            return true;

            $order = Order::find()
                ->andWhere(['user_id' => $this->user->id])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['>=', 'status', Order::$statusMapping['PAID']])
                ->select(['id'])
                ->column();

            if ($order) {
                $count = OrderItem::find()
                    ->where(['order_id' => $order])
                    ->andWhere(['product_id' => $product_id])
                    ->count();

                if ($count > 0) {
                    return true;
                }

                // $set = MarketingSecondKill::getLastOne();
                //
                // if ($count > $set->order_quantity) {
                //     return true;
                // }
            }
        }
    }


}